package org.redrock.test.interceptor.impl;

import org.redrock.test.bean.JwtFormData;
import org.redrock.test.exception.WeixinException;
import org.redrock.test.interceptor.BaseInterceptor;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class JwtAuth implements BaseInterceptor {

    String key = JwtFormData.class.toString();

    @Override
    public boolean interceptor(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                        httpServletRequest.getInputStream(), "UTF-8"
                )
        );
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();
        String data = builder.toString();
        System.out.println(data);
        String[] items = data.split("\\.");
        if (httpServletRequest.getHeader("Authorization") == null) throw new WeixinException(HttpStatus.BAD_REQUEST, "验证失败");
        if (items == null || items.length != 3) throw new WeixinException(HttpStatus.BAD_REQUEST, "表单格式有误");
        JwtFormData jwtFormData = new JwtFormData();
        jwtFormData.setToken(httpServletRequest.getHeader("Authorization"));
        jwtFormData.setSignature(items[0]);
        jwtFormData.setHeaders(items[1]);
        jwtFormData.setPayload(items[2]);
        httpServletRequest.setAttribute(key, jwtFormData);
        httpServletRequest.getSession().setAttribute(key, jwtFormData);
        return true;
    }

//    public static void main(String[] args) {
//        String data = "def634f5c1166907f52fc621bb094840527675492e98f766a1a117f7e51b9623.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiamlhbmd0aWFueGluZyIsInBhc3N3b3JkIjoianh4In0=";
//        String[] items = data.split(".");
//
//    }
}
